package cn.aitrox.ry.common.controller;

import cn.aitrox.ry.common.bean.ExportFileCallback;
import cn.aitrox.ry.common.interceptor.UserThreadLocal;
import cn.aitrox.ry.constant.CommonConstant;
import cn.aitrox.ry.util.FsUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

public abstract class BaseController {

    @Autowired
    private UserThreadLocal userThreadLocal;

    protected Integer getUserId() {
        return userThreadLocal.getUser().getId();
    }

    protected ResponseEntity exportFileUseByte(File tmpParentFile, String exportFileName, File exportFile, ExportFileCallback callback) throws IOException {
        try {

            File tmpFile = callback.writeTmpFile(exportFile);
            byte[] bytes = FileUtils.readFileToByteArray(tmpFile);
            String fileNameEncode = URLEncoder.encode(exportFileName, CommonConstant.CHARACTER_UTF8);
            // 写入到输出流
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileNameEncode);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } finally {
            if (tmpParentFile.exists()) {
                FsUtil.deleteDir(tmpParentFile);
            }
        }
    }
}
